<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>业务管理 - 编辑业务</title>
    <link rel="stylesheet" href="../../css/style.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="../../js/utils.js"></script>
    <script src="../../js/api.js"></script>
    <script type="module" src="../../js/components/navigation.js"></script>
</head>
<body>
    <div class="app-container">
        <header class="app-header">
            <div class="logo">员工管理系统</div>
            <div class="user-info">
                <span id="username-display"></span>
                <button id="logout-btn" class="btn btn-secondary">退出登录</button>
            </div>
        </header>

        <div class="app-body">
            <aside class="sidebar">
                <nav class="menu">
                    <ul>
                        <li><a href="#" class="menu-item active" data-target="welcome">欢迎页</a></li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">员工管理</a>
                            <ul class="submenu">
                                <li><a href="../employee/list.html" class="submenu-item">员工列表</a></li>
                                <li><a href="../employee/add.html" class="submenu-item">添加员工</a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">业务管理</a>
                            <ul class="submenu">
                                <li><a href="../business/list.html" class="submenu-item">业务列表</a></li>
                                <li><a href="../business/create.html" class="submenu-item">创建业务</a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">薪酬管理</a>
                            <ul class="submenu">
                                <li><a href="../salary/overview.html" class="submenu-item">薪酬概览</a></li>
                                <li><a href="../salary/manage.html" class="submenu-item">薪酬管理</a></li>
                            </ul>
                        </li>
                        <li class="menu-group">
                            <a href="#" class="menu-item">系统设置</a>
                            <ul class="submenu">
                                <li><a href="../system/user.html" class="submenu-item">用户管理</a></li>
                                <li><a href="../system/profile.html" class="submenu-item">个人设置</a></li>
                            </ul>
                        </li>
                    </ul>
                </nav>
            </aside>

            <main class="content">
                <div class="form-container">
                    <h2 class="form-title">编辑业务</h2>
                    <form id="update-business-form">
                        <input type="hidden" id="id" name="id">
                        <div class="form-group">
                            <label for="name">业务名称 <span style="color: red;">*</span></label>
                            <input type="text" id="name" name="name" placeholder="请输入业务名称">
                        </div>
                        <div class="form-group">
                            <label for="description">业务描述</label>
                            <textarea id="description" name="description" rows="4" placeholder="请输入业务描述"></textarea>
                        </div>
                        <div class="form-group">
                            <label for="startDate">开始日期 <span style="color: red;">*</span></label>
                            <input type="date" id="startDate" name="startDate">
                        </div>
                        <div class="form-group">
                            <label for="endDate">结束日期 <span style="color: red;">*</span></label>
                            <input type="date" id="endDate" name="endDate">
                        </div>
                        <div class="form-group">
                            <label for="status">状态 <span style="color: red;">*</span></label>
                            <select id="status" name="status">
                                <option value="">请选择状态</option>
                                <option value="未开始">未开始</option>
                                <option value="进行中">进行中</option>
                                <option value="已完成">已完成</option>
                                <option value="已暂停">已暂停</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <label for="revenue">预计收入 <span style="color: red;">*</span></label>
                            <input type="number" id="revenue" name="revenue" placeholder="请输入预计收入" step="0.01">
                        </div>
                        <div class="action-buttons">
                            <button type="submit" class="btn btn-primary">保存</button>
                            <a href="list.html" class="btn btn-secondary">取消</a>
                        </div>
                    </form>
                </div>
            </main>
        </div>
    </div>

    <script>
        $(document).ready(function() {
            // 检查登录状态
            checkLoginStatus();

            // 显示用户名
            const username = localStorage.getItem('username');
            if (username) {
                $('#username-display').text(username);
            }

            // 退出登录
            $('#logout-btn').click(function() {
                localStorage.removeItem('token');
                localStorage.removeItem('username');
                window.location.href = '../../index.html';
            });

            // 获取URL参数中的业务ID
            const urlParams = new URLSearchParams(window.location.search);
            const businessId = urlParams.get('id');

            if (!businessId) {
                alert('未找到业务ID');
                window.location.href = 'list.html';
            } else {
                // 加载业务详情
                loadBusinessDetails(businessId);
            }

            // 表单提交事件
            $('#update-business-form').submit(function(e) {
                e.preventDefault();

                // 表单验证
                if (!validateForm()) {
                    return;
                }

                // 获取表单数据
                const formData = {
                    id: $('#id').val().trim(),
                    name: $('#name').val().trim(),
                    description: $('#description').val().trim(),
                    startDate: $('#startDate').val().trim(),
                    endDate: $('#endDate').val().trim(),
                    status: $('#status').val().trim(),
                    revenue: parseFloat($('#revenue').val().trim())
                };

                // 提交表单数据
                window.api.business.update(formData)
                    .then(response => {
                        if (response) {
                            alert('更新成功');
                            window.location.href = 'list.html';
                        } else {
                            alert('更新失败');
                        }
                    })
                    .catch(error => {
                        console.error('Failed to update business:', error);
                        alert('更新失败，请重试');
                    });
            });

            function checkLoginStatus() {
                const token = localStorage.getItem('token');
                if (!token) {
                    window.location.href = '../../index.html';
                }
            }

            function loadBusinessDetails(id) {
                window.api.business.getById(id)
                    .then(business => {
                        if (business) {
                            // 填充表单数据
                            $('#id').val(business.id);
                            $('#name').val(business.name);
                            $('#description').val(business.description);
                            $('#startDate').val(business.startDate);
                            $('#endDate').val(business.endDate);
                            $('#status').val(business.status);
                            $('#revenue').val(business.revenue);
                        } else {
                            alert('未找到业务信息');
                            window.location.href = 'list.html';
                        }
                    })
                    .catch(error => {
                        console.error('Failed to load business details:', error);
                        alert('加载业务详情失败，请重试');
                    });
            }

            function validateForm() {
                let isValid = true;

                // 验证业务名称
                const name = $('#name').val().trim();
                if (!name) {
                    alert('请输入业务名称');
                    isValid = false;
                }

                // 验证开始日期
                const startDate = $('#startDate').val().trim();
                if (!startDate || !Validator.isDate(startDate)) {
                    alert('请选择有效的开始日期');
                    isValid = false;
                }

                // 验证结束日期
                const endDate = $('#endDate').val().trim();
                if (!endDate || !Validator.isDate(endDate)) {
                    alert('请选择有效的结束日期');
                    isValid = false;
                }

                // 验证日期顺序
                if (startDate && endDate && new Date(startDate) > new Date(endDate)) {
                    alert('开始日期不能晚于结束日期');
                    isValid = false;
                }

                // 验证状态
                const status = $('#status').val().trim();
                if (!status) {
                    alert('请选择状态');
                    isValid = false;
                }

                // 验证预计收入
                const revenue = $('#revenue').val().trim();
                if (!revenue || !Validator.isMoney(revenue) || revenue <= 0) {
                    alert('请输入有效的预计收入');
                    isValid = false;
                }

                return isValid;
            }
        });
    </script>
</body>
</html>